package com.heima.behavior.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.heima.behavior.pojos.ApArticleLikes;
import com.heima.behavior.service.ArticleLikesService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.LikesDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppThreadLocalUtil;
import com.mongodb.client.AggregateIterable;
import io.micrometer.core.instrument.util.JsonUtils;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;

@Service
@AllArgsConstructor
public class ArticleLikesServiceImpl implements ArticleLikesService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Override
    public ResponseResult getLikes(LikesBehaviorDto dto) {
        Integer userId = AppThreadLocalUtil.getUser();
        //0 点赞   1 取消点赞
        Short operation = dto.getOperation();
        if (operation == 0){
            ApArticleLikes apArticleLikes = new ApArticleLikes();
            apArticleLikes.setArticleId(dto.getArticleId());
            apArticleLikes.setUserId((long)userId);
            apArticleLikes.setType(dto.getType());
            apArticleLikes.setOperation(operation);
            apArticleLikes.setCreateTime(LocalDateTime.now());
            apArticleLikes.setUpdateTime(LocalDateTime.now());
            mongoTemplate.save(apArticleLikes);
        } else if (operation == 1) {
            mongoTemplate.remove(Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("userId").is(userId)), ApArticleLikes.class);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public Boolean isLike(LikesBehaviorDto dto) {
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("userId").is(AppThreadLocalUtil.getUser()));
        ApArticleLikes one = mongoTemplate.findOne(query, ApArticleLikes.class);
        return ObjectUtils.isNotEmpty(one);
    }

    @Override
    public void getArticleLikes() {
        AggregationOperation groupOperation = Aggregation.group("articleId")
                .addToSet("userId").as("uniqueUserIds")
                .count().as("likesCounts").first("articleId").as("articleId");
        Aggregation aggregation = Aggregation.newAggregation(groupOperation);
        ArrayList<LikesDto> likesDtos = new ArrayList<>();
        AggregationResults<LikesDto> results = mongoTemplate.aggregate(aggregation, "ap_like", LikesDto.class);
        List<LikesDto> mappedResults = results.getMappedResults();
        String result = JSONArray.toJSONString(mappedResults);
       // String result = mongoTemplate.findAll(ApArticleLikes.class).toString();
        kafkaTemplate.send("leadnews_likes_topic",result);
    }

}
